#标准库，用于创建图形用户界面（GUI），支持窗口、按钮、文本框等控件的创建和管理。
import tkinter as tk
from tkinter import PhotoImage
#第三方库，用于图像处理，支持图像打开、编辑、保存、格式转换等操作。Pillow 是 PIL 的现代分支，功能更强大且兼容性更好。
from PIL import Image, ImageTk, ImageDraw, ImageFont
from .Shared import *

player = shareddata.get_player()

#战斗界面
class PageFight(tk.Frame):

    def __init__(self, parent):
        super().__init__(parent)
        self.configure(bg = "white", width = 1200, height = 720)
        # 禁止自动调整大小
        self.pack_propagate(False) 
        self.bind("<Expose>", lambda event: self.on_raise(event, parent))
        parent.init_framesC()
        global player
        player = shareddata.get_player()

        #加载界面变量
        #界面按钮
        self.pagebuttonlist = []
        self.pagebuttontextlist = ["PageHome", "PageRole", "PageForge", "PageFight", "PageSet"]
        self.pagebuttonid = []
        self.nowpage = 3
        #章节按钮
        self.chapterbuttonlist = []
        self.chapterbuttontextlist = ["The 1'st", "The 2'nd", "The 3'rd", "The 4'th", "The 5'th", "The 6'th", "The 7'th", "The 8'th", "The 9'th", "The 10'th"]
        self.chapterbuttonid = []
        self.nowchapter = 0
        #关卡按钮
        self.fightbuttonlist = []
        self.fightbuttontextlist = ["1", "2", "3", "4", "5"]
        self.fightbuttonid = []
        self.nowfight = 0

        self.equipmentlist = [["weapon", "enchant"], ["clothes", "core"], ["shoes", "medal"]]

        #加载图像资源
        self.picture ={
            "PageFight": shareddata.get_picture("PageFight"),
            "Resources": shareddata.get_picture("Resources")
        }
        self.chapter = shareddata.get_chapter()
        #加载动画缓冲画布
        self.buffer_image = Image.new("RGBA", (1200, 720), (255, 255, 255, 0))
        self.canvas = tk.Canvas(self, width = 1200, height = 720, highlightthickness = 0, bd = 0)
        self.canvas.place(x = 0, y = 0)

        #界面按钮
        for i in range(5):
            self.pagebuttonlist.append(tk.Canvas(self, bg = "#FFFFFF" if (i != self.nowpage) else "#87CEFA", width = 80, height = 80, highlightthickness = 0, bd = 0))
            self.pagebuttonlist[i].place(x = 600 + 120 * i, y = 10)
            self.pagebuttonid.append(self.pagebuttonlist[i].create_image(0, 0, anchor = tk.NW, image = self.picture["Resources"]["ButtonList"][i][1]))
            self.pagebuttonlist[i].bind("<Enter>", lambda event, i = i: self.mouse_enter(event, self.nowpage, i, self.pagebuttonlist[i]))
            self.pagebuttonlist[i].bind("<Leave>", lambda event, i = i: self.mouse_leave(event, self.nowpage, i, self.pagebuttonlist[i]))
            self.pagebuttonlist[i].bind("<Button-1>", lambda event, i = i: parent.show_frame(self.pagebuttontextlist[i]))

        #章节按钮
        for i in range(10):
            self.chapterbuttonlist.append(tk.Canvas(self, bg = "#FFFFFF" if (i != self.nowchapter) else "#87CEFA", width = 200, height = 60, highlightthickness = 0, bd = 0))
            self.chapterbuttonlist[i].place(x = 0, y = 120+60*i)
            self.chapterbuttonid.append(self.chapterbuttonlist[i].create_text(100, 30, anchor = tk.CENTER, text = self.chapterbuttontextlist[i], fill = "black", font = (shareddata.get_font_path(), 25)))
            self.chapterbuttonlist[i].bind("<Enter>", lambda event, i = i: self.mouse_enter(event, self.nowchapter, i, self.chapterbuttonlist[i]))
            self.chapterbuttonlist[i].bind("<Leave>", lambda event, i = i: self.mouse_leave(event, self.nowchapter, i, self.chapterbuttonlist[i]))
            self.chapterbuttonlist[i].bind("<Button-1>", lambda event, i = i: self.show_chapter(i))
            
        #关卡按钮
        for i in range(5):
            self.fightbuttonlist.append(tk.Canvas(self, bg = "#FFFFFF" if (i != self.nowfight) else "#87CEFA", width = 100, height = 100, highlightthickness = 0, bd = 0))
            self.fightbuttonlist[i].place(x = 300 + 180 * i, y = 200 + 300 * (i % 2))
            self.fightbuttonid.append(self.fightbuttonlist[i].create_text(50, 50, anchor = tk.CENTER, text = str(self.nowchapter+1) + "-" + self.fightbuttontextlist[i], fill = "black", font = (shareddata.get_font_path(), 25)))
            self.fightbuttonlist[i].bind("<Enter>", lambda event, i = i: self.mouse_enter(event, self.nowfight, i, self.fightbuttonlist[i]))
            self.fightbuttonlist[i].bind("<Leave>", lambda event, i = i: self.mouse_leave(event, self.nowfight, i, self.fightbuttonlist[i]))
            self.fightbuttonlist[i].bind("<Button-1>", lambda event, i = i: self.show_fight(parent, i))

        #动画缓冲
        self.update_buffer(parent)

    #界面抬升触发事件
    def on_raise(self, event, parent):
        global player
        player = shareddata.get_player()
        self.update_buffer(parent) 

    #动画缓冲之画面上传
    def update_buffer(self, parent):
        self.buffer_image.paste((255, 255, 255, 0), [0, 0, 1200, 720])
        self.draw_to_buffer(self.buffer_image, parent)
        self.photo_buffer = ImageTk.PhotoImage(self.buffer_image)
        self.canvas.create_image(0, 0, image = self.photo_buffer, anchor = tk.NW)

    #动画缓冲之绘制缓冲画面
    def draw_to_buffer(self, buffer_image, parent):
        global player
        player = shareddata.get_player()
        draw = ImageDraw.Draw(buffer_image)
        headfont = ImageFont.truetype(shareddata.get_font_path(), 30)
        smallfont = ImageFont.truetype(shareddata.get_font_path(), 15)
        draw.rectangle([0, 0, 1200, 720], fill=(255, 255, 255, 0)) 
        #背景
        #buffer_image.paste(self.picture["PageFight"]["BackGround"][0], (0, 0), self.picture["PageFight"]["BackGround"][0])
        #左上头像框   
        buffer_image.paste(self.picture["Resources"]["HeadFrame"][0], (0, 0), self.picture["Resources"]["HeadFrame"][0]) 
        buffer_image.paste(self.picture["Resources"]["KianaHead"][0], (20, 10), self.picture["Resources"]["KianaHead"][0]) 
        buffer_image.paste(self.picture["Resources"]["Crystal"][0], (120, 50), self.picture["Resources"]["Crystal"][0]) 
        buffer_image.paste(self.picture["Resources"]["Coin"][0], (270, 50), self.picture["Resources"]["Coin"][0]) 
        draw.text((120, 15), player["neckname"], font = headfont) 
        draw.text((270, 15), "LV." + str(player["level"]), font = headfont) 
        draw.text((150, 50), ":" + str(player["crystal"]), font = headfont) 
        draw.text((300, 50), ":" + str(player["coin"]), font = headfont)  
        
    def mouse_enter(self, event, cls, now, canvas):
        canvas.config(bg = "#FFD700" if (now != cls) else "#87CEFA")

    def mouse_leave(self, event, cls, now, canvas):
        canvas.config(bg = "#FFFFFF"  if (now != cls) else "#87CEFA")

    def show_chapter(self, now):
        self.chapterbuttonlist[self.nowchapter].config(bg = "#FFFFFF")
        self.nowchapter = now
        self.chapterbuttonlist[self.nowchapter].config(bg = "#87CEFA")
        for i in range(5):
            self.fightbuttonlist[i].itemconfig(self.fightbuttonid[i],  text = str(self.nowchapter+1) + "-" + self.fightbuttontextlist[i], fill = "black", font = (shareddata.get_font_path(), 25))   
        self.update_buffer(self.master)

    def show_fight(self, parent, now):
        # 更新当前选中的战斗按钮样式
        self.fightbuttonlist[self.nowfight].config(bg="#FFFFFF")
        self.nowfight = now
        self.fightbuttonlist[self.nowfight].config(bg="#87CEFA")
        # 清除之前可能存在的子Frame
        if hasattr(self, 'fight_subframe'):
            self.fight_subframe.destroy()
        # 创建子Frame
        self.fight_subframe = tk.Frame(self, bg="white", relief=tk.RAISED, highlightthickness = 0, bd = 0)
        self.fight_subframe.place(x=200, y=60, width=800, height=600)  # 调整位置和大小
        # 在子Frame中添加内容
        self._setup_fight_subframe(parent)
        self.update_buffer(self.master)

    def _setup_fight_subframe(self, parent):
        """设置战斗详情子Frame的内容"""
        # 添加标题
        title_label = tk.Label(
            self.fight_subframe, 
            text=f"第 {self.nowchapter+1} 章 - 第 {self.fightbuttontextlist[self.nowfight]} 关",
            font=(shareddata.get_font_path(), 24),
            bg="white"
        )
        title_label.pack(pady=10)
        # 添加图像
        try:
            # 使用Pillow处理图像
            fight_img = Image.open(f"path_to_your_fight_images/{self.nowchapter+1}_{self.nowfight+1}.png")  # 假设有对应图片
            fight_img = fight_img.resize((400, 250), Image.Resampling.LANCZOS)
            self.fight_photo = ImageTk.PhotoImage(fight_img)
            
            img_label = tk.Label(self.fight_subframe, image=self.fight_photo, bg="white")
            img_label.pack(pady=10)
        except Exception as e:
            print(f"无法加载战斗图片: {e}")
            # 添加占位文本
            placeholder = tk.Label(
                self.fight_subframe, 
                text="战斗预览图", 
                bg="lightgray", 
                width=50, 
                height=15
            )
            placeholder.pack(pady=10)
        
        # 添加描述文本
        desc_text = tk.Text(
            self.fight_subframe, 
            width=60, 
            height=8,
            font=(shareddata.get_font_path(), 12),
            wrap=tk.WORD,
            bg="white",
            bd=0
        )
        desc_text.insert(tk.END, f"这是第 {self.nowchapter+1} 章第 {self.fightbuttontextlist[self.nowfight]} 关的详细描述...\n\n敌人类型: 自己进去看喵\n推荐等级: {self.chapter[self.nowchapter*5+self.nowfight]['providelevel']}")
        desc_text.config(state=tk.DISABLED)  # 设置为只读
        desc_text.pack(pady=10)
        
        # 添加按钮区域
        button_frame = tk.Frame(self.fight_subframe, bg="white")
        button_frame.pack(pady=10)
        # 取消按钮
        cancel_btn = tk.Button(
            button_frame,
            text="返回",
            font=(shareddata.get_font_path(), 16),
            bg="#f44336",
            fg="white",
            command=lambda: self.fight_subframe.destroy()
        )
        cancel_btn.pack(side=tk.LEFT, padx=20)       
        # 开始战斗按钮
        start_btn = tk.Button(
            button_frame,
            text="开始战斗",
            font=(shareddata.get_font_path(), 16),
            bg="#4CAF50",
            fg="white",
            command=lambda: self._start_fight(parent)
        )
        start_btn.pack(side=tk.LEFT, padx=20)
        

    def _start_fight(self, parent):
        global player
        player = shareddata.get_player()
        player["fight"] = str(self.nowchapter+1) + "-" + str(self.nowfight+1)
        shareddata.set_player(player)
        print(f"开始战斗: 第 {self.nowchapter+1} 章第 {self.fightbuttontextlist[self.nowfight]} 关")
        # 这里可以添加实际开始战斗的逻辑
        # 例如切换到战斗场景或显示战斗动画
        # 显示一个消息框
        #from tkinter import messagebox
        #messagebox.showinfo(
        #    "战斗开始",
        #    f"正在进入第 {self.nowchapter+1} 章第 {self.fightbuttontextlist[self.nowfight]} 关的战斗!"
        #)
        parent.show_frame("PageZhandoushuang")
